/**
 * 历史导航菜单选项卡
 * @type object
 * @since 1.0 <2015-6-19> SoChishun Added.
 * @since 2.0 <2015-6-23> SoChishun 重构为 indexedDB引擎
 */
var SuNavTab = {
    newInstance: function () {
        var obj = {
            db: null,
            config: {
                debug: false,
                startup: 0,
                store_name: 'nav_tab',
                sign: 'nav_tab',
                container_id: '',
                max_count: 10,
                redirect_fn: function (id) {

                }
            },
            /**
             * 设置配置选项
             * @param object option
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            set_config: function (option) {
                $.extend(this.config, option);
            },
            /**
             * 记录日志
             * @param string fn
             * @param string msg
             * @since 1.0 <2015-6-23> SoChishun Added.
             */
            log: function (fn, msg) {
                if (this.config.debug) {
                    console.log('SuNavTab 2.0 [' + fn + ']: ' + msg);
                }
            },
            /**
             * 打开数据库
             * @since 1.0 <2015-6-23> SoChishun Added.
             */
            open_db: function () {
                if (!window.indexedDB)
                {
                    alert("你的浏览器不支持IndexedDB,请更换为现代浏览器!");
                    return;
                }
                var version = 3;
                var request = window.indexedDB.open(this.config.store_name, version);
                request.onerror = function (e) {
                    obj.log('open_db', e.currentTarget.error.message);
                };
                request.onsuccess = function (e) {
                    obj.db = e.target.result;
                    obj.log('open_db', 'Open Success!');
                };
                request.onupgradeneeded = function (e) {
                    var db = e.target.result;
                    if (db.objectStoreNames.contains(obj.config.store_name)) {
                        obj.log('open_db.onupgradeneeded', 'delete success');
                        db.deleteObjectStore(obj.config.store_name);
                    }
                    db.createObjectStore(obj.config.store_name, {keyPath: 'sign'});
                    obj.log('open_db', 'DB version changed to ' + version);
                };
            },
            init: function () {
                this.open_db();
            },
            /**
             * 生成tab
             * @param Array menus
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            build_tab: function (menus) {
                if (!menus) {
                    return;
                }
                var req = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                req.onerror = function (e) {
                    obj.log('build_tab', e.currentTarget.error.message);
                }
                req.onsuccess = function (e) {
                    var otxt = e.target.result;
                    if (!otxt) {
                        // 如果无数据则生成默认起始页
                        otxt = {sign: obj.config.sign, items: [obj.config.startup], current: obj.config.startup};
                    }
                    var $container = $(obj.config.container_id);
                    $(menus).each(function () {
                        $(this.children).each(function () {
                            $(this.children).each(function () {
                                if ($.inArray(Number(this.id), otxt.items) > -1) {
                                    $container.append('<li' + (this.id == otxt.current ? ' class="cur"' : '') + '><a href="/index.php/XCall_5_0' + this.url.substring(16) + '" data-id="' + this.id + '">' + this.name + '</a><i></i></li>');
                                }
                            })
                        })
                    })
                }
            },
            /**
             * 新增Tab或激活Tab
             * @param int id
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            add: function (id) {
                if (!id) {
                    return;
                }
                var req = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                req.onerror = function (e) {
                    obj.log('add', e.currentTarget.error.message);
                }
                req.onsuccess = function (e) {
                    var otxt = e.target.result;
                    if (!otxt) {
                        otxt = {sign: obj.config.sign, items: [id]};
                    } else {
                        if ($.inArray(Number(id), otxt.items) < 0) {
                            otxt.items.push(id); // 追加到末尾
                            if (otxt.items.length > obj.config.max_count) {
                                otxt.shift(); // 如果超过最大数量则删除第一个
                            }
                        }
                    }
                    otxt.current = id;
                    obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).put(otxt);
                }
            },
            /**
             * 删除tab
             * @param int id
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            remove: function (id) {
                if (!id) {
                    return;
                }
                var req = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                req.onerror = function (e) {
                    obj.log('remove', e.currentTarget.error.message);
                }
                req.onsuccess = function (e) {
                    var otxt = e.target.result;
                    if (!otxt) {
                        return;
                    }
                    var idx = $.inArray(Number(id), otxt.items);
                    if (idx < 0) {
                        return; // id不存在,直接退出
                    }
                    if (otxt.items.length < 2) {
                        obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).clear(); // 如果已空了则删除数据库
                        obj.config.redirect_fn(obj.config.startup);
                        return;
                    }
                    if (otxt.items.length > (idx + 1)) {
                        // 如果后面还有tab,则焦点放在后一个
                        otxt.current = otxt.items[idx + 1];
                    } else {
                        // 焦点放在前一个
                        otxt.current = otxt.items[idx - 1];
                    }
                    otxt.items.splice(idx, 1); // 删除已存在的id
                    obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).put(otxt);
                    obj.config.redirect_fn(otxt.current);
                }
            },
            /**
             * 激活标签
             * @param int id
             * @since 1.0 <2015-6-19> SoChishun Added.
             */
            active: function (id) {
                if (!id) {
                    return;
                }
                var store = this.db.transaction([this.config.store_name], 'readonly').objectStore(this.config.store_name).get(this.config.sign);
                store.onerror = function (e) {
                    obj.log('active', e.currentTarget.error.message);
                }
                store.onsuccess = function (e) {
                    var otxt = e.target.result;
                    if (!otxt) {
                        return;
                    }
                    otxt.current = id;
                    obj.db.transaction([obj.config.store_name], 'readwrite').objectStore(obj.config.store_name).put(otxt);
                }
            }
        };
        return obj;
    }
}